package com.dingwei.superiordiary.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.easyViewHolder.UserCenterListAdapter;
import com.dingwei.superiordiary.app.MyApplication;
import com.dingwei.superiordiary.bean.LookUserCenterBean;
import com.dingwei.superiordiary.event.MessageEvent;
import com.dingwei.superiordiary.mvp.presenter.LookUserCenterPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.utils.ScrollCalculatorHelper;
import com.jaeger.library.StatusBarUtil;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.ScreenUtils;
import com.lihao.baselibrary.weight.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author 南柯一梦丶
 * Created time 2018/10/23.
 * Personal signature 余生还长 何必慌张
 * Page description :
 * .::::.
 * .::::::::.
 * :::::::::::
 * ..:::::::::::'
 * '::::::::::::'
 * .::::::::::
 * '::::::::::::::..
 * ..::::::::::::.
 * ``::::::::::::::::
 * ::::``:::::::::'        .:::.
 * ::::'   ':::::'       .::::::::.
 * .::::'      ::::     .:::::::'::::.
 * .:::'       :::::  .:::::::::' ':::::.
 * .::'        :::::.:::::::::'      ':::::.
 * .::'         ::::::::::::::'         ``::::.
 * ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 * '.:::::'                    ':'````..
 */
public class LookUserCenterActivity extends BaseActivity implements Contract.LookUserCenterView {
    LookUserCenterPresenter lookUserCenterPresenter = new LookUserCenterPresenter(this);


    String user_id;
    int page = 1;
    UserCenterListAdapter adapter;


    UserCenterHeaderView headerView;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.main_titleBar)
    TitleBar mainTitleBar;
    @Bind(R.id.ll_title)
    LinearLayout llTitle;
    @Bind(R.id.data_layout)
    RelativeLayout dataLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;
    private LinearLayoutManager layoutManager;
    private ScrollCalculatorHelper scrollCalculatorHelper;
    boolean mFull = false;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_my_user_center;
    }

    @Override
    protected void initData() {
        lookUserCenterPresenter.getUserCenter(user_id, page, true, true);
    }

    @Override
    protected void initView() {

        user_id = getIntent().getStringExtra("user_id");
        StatusBarUtil.setTranslucentForImageView(this, 30, null);


        layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.addItemDecoration(new DividerDecoration(getResources().getColor(R.color.bg), 8));
        adapter = new UserCenterListAdapter(this);
        headerView = new UserCenterHeaderView();
        adapter.addHeader(headerView);
        recyclerView.setAdapter(adapter);


        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshLayout) {
                page = page + 1;
                lookUserCenterPresenter.getUserCenter(user_id, page, false, false);
            }
        });

        mainTitleBar.setOnMenuListener(new TitleBar.OnMenuListener() {
            @Override
            public void onMenuClick() {
                lookUserCenterPresenter.showMeunPopupWindow(mainTitleBar.getMenu(),bean.data.is_black);
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initListener() {

        adapter.xxInterfaceListener(new UserCenterListAdapter.xxInterFace() {
            @Override
            public void showRightDialog(int position, View view) {
                LookUserCenterBean.DataBean.ListBean bean = adapter.getItem(position);

                if (BaseActivity.value.getUserId().equals(LookUserCenterActivity.this.bean.data.info.id)) {
                    lookUserCenterPresenter.showMinePop(view, bean.id, position, bean.top);
                } else {
                    lookUserCenterPresenter.showOtherPop(view, bean.id, position);
                }
            }

            @Override
            public void showShareDialog(int position, View view) {
                LookUserCenterBean.DataBean.ListBean bean = adapter.getItem(position);
                share_id = bean.id;
                lookUserCenterPresenter.showSharePopupWindow(view, bean, position, shareListener);
            }

            @Override
            public void likes(int position) {
                LookUserCenterBean.DataBean.ListBean bean = adapter.getItem(position);
                lookUserCenterPresenter.like(bean.id, position);
            }

            @Override
            public void forward(int position) {
                LookUserCenterBean.DataBean.ListBean bean = adapter.getItem(position);
                intent = new Intent(BaseActivity.context, ForwardEditingActiivty1.class);
                intent.putExtra("bean", bean);
                startActivity(intent);
            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LookUserCenterBean.DataBean.ListBean bean = adapter.getItem(position);
                if (bean.istranspond.equals("0")) {
                    intent = new Intent(BaseActivity.context, FindDetailsActivity.class);
                    intent.putExtra("id", bean.id);
                    startActivity(intent);
                } else {
                    intent = new Intent(BaseActivity.context, FindDetailsActivity.class);
                    intent.putExtra("id", bean.transpond_content.id);
                    startActivity(intent);
                }

            }
        });

        int playTop = ScreenUtils.getScreenHeight(BaseActivity.context) / 4;
        int playBottom = ScreenUtils.getScreenHeight(BaseActivity.context) / 4 * 3;
        //自定播放帮助类
        scrollCalculatorHelper = new ScrollCalculatorHelper(R.id.video_item_player, playTop, playBottom);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                scrollCalculatorHelper.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();

                //这是滑动自动播放的代码
                if (!mFull) {
                    scrollCalculatorHelper.onScroll(recyclerView, firstVisibleItem, lastVisibleItem, lastVisibleItem - firstVisibleItem + 1);
                }
            }
        });

        headerView.btnOperating.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseActivity.value.getUserId().equals(bean.data.info.id)) {
                    intent = new Intent(BaseActivity.context, PersonalDataActivity.class);
                    startActivity(intent);
                } else {
                    if (bean.data.is_attention == 1) {
                        lookUserCenterPresenter.attentionAction(bean.data.info.id, "0");
                    } else {
                        lookUserCenterPresenter.attentionAction(bean.data.info.id, "1");

                    }
                }
            }
        });

        headerView.postLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseActivity.value.getUserId().equals(user_id)) {
                    intent = new Intent(BaseActivity.context, MyPostsActivity.class);
                    intent.putExtra("userid", user_id);
                    startActivity(intent);
                } else {
                    intent = new Intent(BaseActivity.context, HisPostsActivity.class);
                    intent.putExtra("userid", user_id);
                    startActivity(intent);
                }

            }
        });
        headerView.carePersonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(BaseActivity.context, MyCarePersonalActivity.class);
                intent.putExtra("userid", user_id);
                startActivity(intent);
            }
        });
        headerView.careMeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(BaseActivity.context, MyCareMeActivity.class);
                intent.putExtra("userid", user_id);
                startActivity(intent);
            }
        });

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }


    @Override
    public void onFail() {
        showData("fail");
    }

    @Override
    public void onLoadMore(LookUserCenterBean bean) {

        adapter.addAll(bean.data.list);

        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();

        showData("success");
    }

    LookUserCenterBean bean;

    @Override
    public void onRefresh(LookUserCenterBean bean) {

        this.bean = bean;
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();

        Glide.with(BaseActivity.context)
                .load(bean.data.info.portrait)
                .apply(MyApplication.headOptions)
                .into(headerView.imgHead);
        headerView.tvNickName.setText(bean.data.info.nickname);
        headerView.tvIdiograph.setText(bean.data.info.idiograph);
        headerView.tvLevel.setText("LV." + bean.data.info.level);
        if (BaseActivity.value.getUserId().equals(user_id)) {
            headerView.btnOperating.setText("编辑");
            headerView.btnOperating.setBackgroundColor(getResources().getColor(R.color.text_color_gray));
            headerView.tv_care_name.setText("我关注的人");
            headerView.tv_care_person_name.setText("关注我的人");
            mainTitleBar.setMenuImageDrawable(null);
        } else {
            mainTitleBar.setMenuImageResource(R.mipmap.diandiandian);
            headerView.tv_care_name.setText("TA关注的人");
            headerView.tv_care_person_name.setText("关注TA的人");
            if (bean.data.is_attention == 0) {

                headerView.btnOperating.setText("+关注");
                headerView.btnOperating.setBackgroundColor(getResources().getColor(R.color.theme_color));
            } else {
                headerView.btnOperating.setText("已关注");
                headerView.btnOperating.setBackgroundColor(getResources().getColor(R.color.text_color_gray));
            }
        }
        headerView.tvPost.setText("" + bean.data.statistics.activityNumber);
        headerView.tvCarePerson.setText("" + bean.data.statistics.myAttentionNumber);
        headerView.tvCareMe.setText("" + bean.data.statistics.AttentionMeNumber);
        headerView.tvPraise.setText("" + bean.data.statistics.activityCommentLikeNumber);

        adapter.clear();
        adapter.notifyDataSetChanged();
        adapter.addAll(bean.data.list);

        showData("success");

    }

    @Override
    public void collectSuccess(int position) {
        showToast("收藏成功");
    }

    @Override
    public void SetActivityTopSuccess(int position, String top) {
        LookUserCenterBean.DataBean.ListBean bean = adapter.getItem(position);
        if (bean.top.equals("1")) {
            bean.top = "0";
        } else {
            bean.top = "1";
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void DeleteSuccess(int position) {
        adapter.remove(position);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void likeSuccess(int position) {
        adapter.getItem(position).likes = (Integer.parseInt(adapter.getItem(position).likes) + 1) + "";
        adapter.getItem(position).is_likes = 1;
        adapter.notifyDataSetChanged();
    }

    @Override
    public void attentionActionSuccess() {
        bean.data.is_attention = bean.data.is_attention == 0 ? 1 : 0;
        if (bean.data.is_attention == 0) {
            headerView.btnOperating.setText("+关注");
            headerView.btnOperating.setBackgroundColor(getResources().getColor(R.color.theme_color));
        } else {
            headerView.btnOperating.setText("已关注");
            headerView.btnOperating.setBackgroundColor(getResources().getColor(R.color.text_color_gray));
        }
    }

    @Override
    public void lahei() {
        lookUserCenterPresenter.joinBlackList(user_id);
    }

    @Override
    public void jubao() {
        Intent intent = new Intent(BaseActivity.context, ReportActivity.class);
        intent.putExtra("id", user_id);
        intent.putExtra("tip_type", "user");
        BaseActivity.context.startActivity(intent);
    }

    @Override
    public void joinBlackListSuccess() {
        bean.data.is_black = bean.data.is_black==0?1:0;
    }


    public void showData(String state) {
        if (state.equals("success")) {
            noNetLayout.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);
            if (adapter.getAllData() != null && adapter.getAllData().size() > 0) {
                recyclerView.setVisibility(View.VISIBLE);
                noDataLayout.setVisibility(View.GONE);
            } else {
                recyclerView.setVisibility(View.GONE);
                noDataLayout.setVisibility(View.VISIBLE);
            }
        } else {
            refreshLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }


    String share_id;
    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeShowDialog(dialog);
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(LookUserCenterActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            SocializeUtils.safeCloseDialog(dialog);
            lookUserCenterPresenter.shareSuccess(share_id);

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LookUserCenterActivity.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LookUserCenterActivity.this, "取消分享", Toast.LENGTH_LONG).show();

        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        headerView.tvIdiograph.setText(event.getMessage());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }
}
